import Taro from '@tarojs/taro'

// const baseUrl = "https://expression.anchengit.com/v3.2.0/api/"
// const baseUrl = "https://api.sticker.anchengit.com/"


const baseUrl = process.env.TARO_APP_BASE_URL

async function post(url, data){
  const token = Taro.getStorageSync("token");

  const result =  await Taro.request({
    url: baseUrl + url,
    header: {
      "token": token ? token : ''
    },
    data,
    method: "POST"
  })
  if(result.statusCode == 200){
    if(result.data.code == 0){
      return Promise.resolve(result.data.data)
    }
  }else{
    return Promise.reject(result.message)
  }
}

async function get(url, data){
  const token = Taro.getStorageSync("token");
  const result =  await Taro.request({
    url: baseUrl + url + "?" + new URLSearchParams(data).toString(),
    header: {
      "token": token ? token : ''
    },
    method: "GET"
  })
  if(result.statusCode == 200){
    if(result.data.code == 200){
      return Promise.resolve(result.data.data)
    }else{
      return Promise.reject(result.data)
    }
  }else{
    console.log("error")
  }
}

async function upload(url, name, filePath, data) {
  const result =  await Taro.uploadFile({
    url: baseUrl + url ,
    name,
    filePath,
    data
  })
  if(result.statusCode == 200){
    const data = JSON.parse(result.data);
    if(data.code == 0){
      return Promise.resolve(data.data)
    }else{
      return Promise.reject(data.message)
    }
  }else{
    console.log("error")
  }
}

async function put(url, data){
  return Taro.request({
    url,
    data,
    method: "PUT"
  })
}

async function del(url, data){
  const token = Taro.getStorageSync("token");
  const result =  await Taro.request({
    url: baseUrl + url + "?" + new URLSearchParams(data).toString(),
    header: {
      "token": token ? token : ''
    },
    method: "DELETE"
  })
  if(result.statusCode == 200){
    if(result.data.code == 0){
      return Promise.resolve(result.data.data)
    }else{
      return Promise.reject(result.data)
    }
  }else{
    console.log("error")
  }
}

export { post, put, get, upload, del}


